<template>
  <div class="box">
    <el-form :model="form" label-width="120px" v-loading="loading">
      <div style="display: inline-block">
        <el-form-item label="标题">
          <el-input v-model="form.title" style="width: 200px;" />
        </el-form-item>
        <div style="display: inline-block">
          <el-form-item label="作者">
            <el-select v-model="form.flowerUserId" placeholder="请选择作者">
              <el-option v-for="user in userList" :key="user.id" :value="user.id"
                :label="`${user.nickname} (${user.username})`"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="内容">
          <MdEditor v-model="form.content" noUploadImg />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" @click="onInsert">插入</el-button>
        <el-popconfirm @confirm="clearAll" title="确认清空">
          <template #reference>
            <el-button>清空</el-button>
          </template>
        </el-popconfirm>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { reactive } from 'vue';
import { createArticle } from "@/api/article";
import { getFlowerUserPage } from "@/api/flowerUser";
import { ElMessage } from 'element-plus';
import MdEditor from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
export default {
  name: "articleInsert",
  data() {
    return {
      // do not use same name with ref
      form: reactive({
        flowerUserId: 1,
        title: '',
        content: '',
      }),
      loading: false,
      userList: {},
    }
  },
  components: {
    MdEditor,
  },
  methods: {
    //提交修改
    onInsert() {
      this.loading = true
      const data = this.form;
      return createArticle(data)
        .then((response) => {
          this.$emit('insertSuccess');
          ElMessage.success("插入成功");
          this.clearAll();
          this.loading = false;
        })
        .catch((error) => {
          ElMessage.error("插入失败");
          console.log(error);
        });
    },

    clearAll() {
      this.form = {
        flowerUserId: 1,
        title: '',
        content: '',
      }
    },

    //获取所有的userID和userName
    getAllUserIdAndUserName() {
      this.loading = true;
      const params = {
        size: 9999,
        current: 1,
      };
      return getFlowerUserPage(params)
        .then((response) => {
          this.userList = response.data.data.records;
          this.loading = false;
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  mounted: function () {
    this.getAllUserIdAndUserName();
  }
}


</script>

<style scoped>
.box {
  width: 1200px;
  display: inline-block;
}
</style>